package com.shinhye.wisdompeking.custom;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lidroid.xutils.BitmapUtils;
import com.shinhye.wisdompeking.R;
import com.shinhye.wisdompeking.utils.CommonUtil;

import java.util.ArrayList;
import java.util.List;

public class AutoRollViewPager extends ViewPager {
	private final String TAG = "AutoRollViewPager";
	
	private List<String> imgurls;
	private RollPagerAdapter adapter;
	private List<View> dots;
	private TextView tv_title;
	private List<String> titles;
	private final int MSG = 0x001;
	private OnPagerClick mPagerClick;
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == MSG) {
//				System.out.println(MSG + "--kekeke++" + this.hashCode() + "++keke--" + getCurrentItem());
				int next = (getCurrentItem() + 1) % imgurls.size();
				setCurrentItem(next);
				this.sendEmptyMessageDelayed(MSG, 3000);
			}
		}
	};
	private float downY;
	private float downX;
	
	public AutoRollViewPager(Context context, OnPagerClick pagerClick) {
		super(context);
		this.mPagerClick = pagerClick;
		
		this.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				tv_title.setText(titles.get(position));
				for(int i = 0; i < dots.size(); i++) {
					if(i == position)
						dots.get(i).setBackgroundResource(R.drawable.dot_focus);
					else 
						dots.get(i).setBackgroundResource(R.drawable.dot_normal);
				}
			}
			@Override
			public void onPageScrolled(int position, float positionOffset,
					int positionOffsetPixels) {}
			@Override
			public void onPageScrollStateChanged(int state) {}
		});
	}

	/**
	 * 设置组图地址
	 * @param imgurls
	 */
	public void setImageUrl(List<String> imgurls) {
		this.imgurls = imgurls;
	}
	
	/**
	 * 与指示点关联
	 */
	public void attachDotGroup(LinearLayout dots_ll) {
		if(dots == null) {
			dots = new ArrayList<View>();
		}
		dots_ll.removeAllViews();
		dots.clear();
		
		for(int i = 0; i < imgurls.size(); i++) {
			View view = new View(getContext());
			if(i == this.getCurrentItem()){
				view.setBackgroundResource(R.drawable.dot_focus);
			}else{
				view.setBackgroundResource(R.drawable.dot_normal);
			}
			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
					CommonUtil.dip2px(getContext(), 6), 
					CommonUtil.dip2px(getContext(), 6));
			view.setLayoutParams(layoutParams);
			layoutParams.setMargins(5, 0, 5, 0);
			dots_ll.addView(view);
			dots.add(view);
		}
	}
	
	/**
	 * 与指定标题关联
	 * @param titles 
	 * @param view 
	 */
	public void attachTitle(TextView view, List<String> titles) {
		view.setText(titles.get(this.getCurrentItem()));
		this.tv_title = view;
		this.titles = titles;
	}
	
	/**
	 * 滚动ViewPager
	 */
	public void startRoll() {
		if(imgurls == null) {
			throw new IllegalStateException("没有要设置给AutoRollViewPager的图片，请先调用setImageUrl()方法！");
		}
		if(tv_title == null) {
			throw new IllegalStateException("没有要设置给AutoRollViewPager的图片，请先调用attachTitle()方法！");
		}
		if(dots == null) {
			throw new IllegalStateException("没有要设置给AutoRollViewPager的图片，请先调用attachDotGroup()方法！");
		}
		if(adapter == null) {
			adapter = new RollPagerAdapter();
			this.setAdapter(adapter);
		} else {
			adapter.notifyDataSetChanged();
		}
		
		if(!handler.hasMessages(MSG))
			handler.sendEmptyMessageDelayed(MSG, 3000);
	}
	
	private class RollPagerAdapter extends PagerAdapter {
		@Override
		public int getCount() {
			return imgurls.size();
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}
		
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			ImageView viewpager_item = (ImageView) View.inflate(getContext(), R.layout.viewpager_item, null);
			BitmapUtils bitmapUtils = new BitmapUtils(getContext());
			bitmapUtils.display(viewpager_item, imgurls.get(position));
			container.addView(viewpager_item);
			return viewpager_item;
		}
		
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		switch(ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			Log.i(TAG, "onTouchEvent--DOWN::" + ev.getX());
			handler.removeCallbacksAndMessages(null);
			break;
		case MotionEvent.ACTION_MOVE:
			break;
		case MotionEvent.ACTION_UP:
			Log.i(TAG, "onTouchEvent--UP::" + ev.getX() + "//" + ev.getY());
			if(ev.getEventTime() - ev.getDownTime() < 500 && Math.abs(downX - ev.getX()) < 10 && Math.abs(downY - ev.getY()) < 10) {
				Log.i(TAG, "点击了第" + getCurrentItem() + "个轮播图条目");
				
				if(mPagerClick != null) {
					mPagerClick.onClick(getCurrentItem());
				}
			}
			startRoll();
			break;
		case MotionEvent.ACTION_CANCEL:
			Log.i(TAG, "onTouchEvent--CANCEL::" + ev.getX() + "//" + ev.getY());
			startRoll();
			break;
		}
		return super.onTouchEvent(ev);
	}
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		switch(ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			downX = ev.getX();
			downY = ev.getY();
			
			Log.i(TAG, "dispatchTouchEvent--DOWN::" + downX);
			requestDisallowInterceptTouchEvent(true);
			break;
		case MotionEvent.ACTION_MOVE:
			float moveX = ev.getX();
			float moveY = ev.getY();
			
			if(Math.abs(moveX - downX) < Math.abs(moveY - downY)) {
				requestDisallowInterceptTouchEvent(false);
			}
			
			break;
		case MotionEvent.ACTION_UP:
			break;
		}
		return super.dispatchTouchEvent(ev);
	}
	
	/**
	 * 轮播图被点击的回调接口
	 * @author ShinHye
	 * 2014-10-25 上午1:44:24
	 */
	public interface OnPagerClick {
		/**
		 * 第一个条目被点击了
		 * @param position
		 */
		void onClick(int position);
	}
}
